using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using IGGCore;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Diagnostics;
using IGG.Formatters;
using IGGCore.Parsers;

namespace IGG
{
    /// <summary>
    /// The manager of the command line side of the application
    /// Information requests are sent to the main channel via events
    /// </summary>
    public class IGGController
    {
        private bool m_looping = false;

        private enum VIEWS { GAMEVIEW, MORNINGVIEW, OFFDAY };
        private VIEWS m_currentView = VIEWS.OFFDAY;

        private BoxesManager m_boxesManager;
        private bool m_updated = false;
        private MainChannel m_mainChannel = null;
        private DateTime m_currentDate = DateTime.Now;
        private bool m_statsLoaded = false;
        private bool m_needBoxes = true;

        private string m_story = null;

        private Thread m_twitterThread;
        private bool m_twitterThreadActive = false;

        private DateTime m_lastNewsRefresh = DateTime.Now;
        private DateTime m_lastTransRefresh = DateTime.Now;

        private bool m_requireRefresh = false;
        private ModeDetailedStandingsFormatter standingsFormatter = new ModeDetailedStandingsFormatter();
        private TeamSectionManager teamSectionManager = new TeamSectionManager();
        private StoryManager storyManager = new StoryManager();
        private BillJamesParser m_billJamesParser = new BillJamesParser();

        /// <summary>
        /// Main constructor
        /// </summary>
        public IGGController()
        {
            m_boxesManager = new BoxesManager();
            m_mainChannel = new MainChannel();
            m_mainChannel.Initialize();
            if (ToolBox.YesterdayScores())
            {
                m_currentDate = DateTime.Now.AddDays(-1);
            }
        }

        /// <summary>
        /// Create the Daily Fastball, without loops or threads
        /// </summary>
        public void StartSynchronousPaper()
        {
            int currentPage = 2;
            Output.Clear();
            Output.WriteLine();
            Output.WriteLine(" =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Output.WriteLine(" THE DAILY FASTBALL - " + DateTime.Now.ToLongDateString());
            Output.WriteLine(" Last Updated on " + DateTime.Now.ToLongTimeString());
            Output.WriteLine(" =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE GAMES  
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            ReloadScoreboard(null);
            if (m_mainChannel.ScoreBoard.GamesList.Games.Count > 0)
            {
                m_mainChannel.UpdateBoxscore(m_currentDate);
                m_boxesManager.InitializeBoxedGames(m_mainChannel.ScoreBoard);
                m_mainChannel.UpdateAllBoxscores(m_currentDate, m_mainChannel.ScoreBoard);
                m_boxesManager.BuildBoxes(m_mainChannel.ScoreBoard);

                Output.WriteLine();

                Player[] stars = ThreeStarsCalculator.GetOffensiveThreeStarPlayers(m_mainChannel.ScoreBoard.GamesList.Games);
                if (stars[0] != null && stars[0].GameScore > 0)
                {
                    Output.WriteLine(" OFFENSIVE STARS");
                    ModeOverviewFormatter.FormatStar(1, stars[0]);
                    ModeOverviewFormatter.FormatStar(2, stars[1]);
                    ModeOverviewFormatter.FormatStar(3, stars[2]);
                }


                List<Player> pitchStars = ThreeStarsCalculator.GetPitchingThreeStarPlayers(m_mainChannel.ScoreBoard.GamesList.Games);
                if (pitchStars.Count > 0 && pitchStars[0] != null && pitchStars[0].GameScore > 0)
                {
                    Output.WriteLine(" GREAT PITCHING PERFORMANCES");
                    for (int i = 0; i < 3; i++ )
                    {
                        if (pitchStars.Count > i && pitchStars[i].GameScore > 0)
                        {
                            ModeOverviewFormatter.FormatStar(i + 1, pitchStars[i]);
                        }
                        
                    }
                    Output.WriteLine(" GAMES DETAILS");
                    for (int i = 0; i < 3; i++)
                    {
                        if (m_mainChannel.ScoreBoard.GamesList.SortedGames.Count > i)
                        {
                            if (ToolBox.YesterdayScores() == false && m_mainChannel.ScoreBoard.GamesList.SortedGames[i].Status.Indicator.IsInProgress)
                            {
                                ModeOverviewFormatter.FormatInProgressGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[i]);
                            }
                            else if (m_mainChannel.ScoreBoard.GamesList.SortedGames[0].Status.Indicator.IsTerminated)
                            {
                                ModeOverviewFormatter.FormatTerminatedGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[i], ToolBox.YesterdayScores());
                            }
                        }
                    }
                }
                else if (pitchStars.Count < 1 || (pitchStars[0] == null && stars[0] == null))
                {
                    string start = "Games will start at " + m_mainChannel.ScoreBoard.GamesList.Games[0].StartTime
                        + " " + m_mainChannel.ScoreBoard.GamesList.Games[0].AmPm.ToLower() + ". "
                        + m_mainChannel.ScoreBoard.GamesList.Games.Count + " games today.";
                    Output.FormatLongText(start);
                    Output.WriteLine();
                    ModeOverviewFormatter.FormatNextGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[0]);
                }
                PrintFooter(currentPage++);
            }


            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE SELECTED GAME  
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            if (m_mainChannel.ScoreBoard.SelectedGame != null)
            {
                ModeDetailedGameFormatter formatter = new ModeDetailedGameFormatter();
                formatter.FormatMode(m_mainChannel.ScoreBoard);
                PrintFooter(currentPage++);
            }


            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE NEWS  
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            m_mainChannel.UpdateNews(false);
            if (m_mainChannel.ScoreBoard.News != null && m_mainChannel.ScoreBoard.News.Count > 2)
            {
                for (int i = 0; i < 5; i++)
                {
                    Output.WriteLine();
                    Output.WriteLine(" " + m_mainChannel.ScoreBoard.News[i].Title.ToUpper());
                    Output.FormatLongText(m_mainChannel.ScoreBoard.News[i].Content);
                }
            }
            PrintFooter(currentPage++);


            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  TWITTER 
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            m_mainChannel.UpdateTweets();
            if (m_mainChannel.ScoreBoard.Tweets != null && m_mainChannel.ScoreBoard.Tweets.Length > 0)
            {
                Output.WriteLine();
                for (int i = 0; i < 7; i++)
                {
                    Output.WriteLine(" " + m_mainChannel.ScoreBoard.Tweets[i].Author.ToUpper());
                    Output.FormatLongText(m_mainChannel.ScoreBoard.Tweets[i].Text);
                    Output.WriteLine();
                }
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" PROBLEM: UNABLE TO LOAD TWEETS.");
            }
            PrintFooter(currentPage++);
             

            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE TRANSACTIONS 
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            m_mainChannel.UpdateTransactions();
            if (m_mainChannel.ScoreBoard.Transactions != null && m_mainChannel.ScoreBoard.Transactions.Count > 0)
            {
                new ModeTransactionsFormatter().FormatMode(m_mainChannel.ScoreBoard, 15);
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" PROBLEM: UNABLE TO LOAD TRANSACTIONS.");
            }
            PrintFooter(currentPage++);


            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  TRIVIA 
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            m_mainChannel.LoadHistory();
            m_billJamesParser.LoadPlayer();
            Output.WriteLine();
            Output.WriteLine(" DID YOU KNOW?");
            Output.FormatLongText(m_mainChannel.GetHistoryTidbit());
            FormatBillJames();
            PrintFooter(currentPage++);


            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE STANDINGS & STATS
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            m_mainChannel.UpdateStandings();
            m_mainChannel.UpdateStatistics();

            if (m_mainChannel.ScoreBoard.StandingsNLC != null && m_mainChannel.ScoreBoard.StandingsNLC.Count > 0)
            {
                Output.WriteLine();
                if (m_mainChannel.ScoreBoard.StatsBatting != null && m_mainChannel.ScoreBoard.StatsBatting.Count > 0)
                {
                    standingsFormatter.FormatCombinedMode(m_mainChannel.ScoreBoard);
                }
                else
                {
                    standingsFormatter.FormatMode(m_mainChannel.ScoreBoard);
                }
            }
            else if (m_mainChannel.ScoreBoard.StandingsGrapefruit != null && m_mainChannel.ScoreBoard.StandingsGrapefruit.Count > 0)
            {
                standingsFormatter.FormatCombinedSpringTraining(m_mainChannel.ScoreBoard);
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" PROBLEM: UNABLE TO LOAD STANDINGS.");
            }
            PrintFooter(currentPage++);



            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE TEAM SECTION 
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            new StatManager().TeamCrunchStats(m_mainChannel.ScoreBoard);
            teamSectionManager.LoadTeamSection();
            teamSectionManager.PublishTeamSection();
            PrintFooter(currentPage++);


            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE BASEBALL REFERENCE SECTION
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            m_mainChannel.SetBaseballReferenceTidbit();
            Output.WriteLine(" FROM BASEBALL REFERENCE...");
            Output.WriteLine();
            Output.WriteLine(m_mainChannel.ScoreBoard.BaseballRefTidbit);
            PrintFooter(currentPage++);



            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
            //  THE STORY SECTION 
            //  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

            
            
        }

        /// <summary>
        /// First method called after the constructor (by Program class)
        /// </summary>
        public void StartApplication(bool looping)
        {
            m_looping = looping;
            try
            {
                // START BY UPDATING NEWS AND TWEETS...
                m_mainChannel.UpdateNews(false);
                m_mainChannel.UpdateTweets();
                m_mainChannel.LoadHistory();
                m_billJamesParser.LoadPlayer();
                storyManager.LoadStory();

                // Start Trans Thread
                Thread threadTrans = new Thread(new ThreadStart(LoadTransactions));
                threadTrans.Priority = ThreadPriority.Normal;
                threadTrans.Start();

                // Start Team Thread
                Thread teamThread = new Thread(new ThreadStart(LoadTeamSection));
                teamThread.Priority = ThreadPriority.Normal;
                teamThread.Start();

                // Start Standings Thread
                Thread threadStandings = new Thread(new ThreadStart(LoadStandings));
                threadStandings.Priority = ThreadPriority.BelowNormal;
                threadStandings.Start();

                // Start Stats Thread
                Thread threadStats = new Thread(new ThreadStart(LoadStats));
                threadStats.Priority = ThreadPriority.BelowNormal;
                threadStats.Start();

                // Start BBRef Thread
                Thread threadBBRef = new Thread(new ThreadStart(LoadBaseballRefTidbit));
                threadBBRef.Priority = ThreadPriority.Lowest;
                threadBBRef.Start();

                // Start Twitter Thread
                Thread threadTwitter = new Thread(new ThreadStart(LoadTwitter));
                threadTwitter.Priority = ThreadPriority.BelowNormal;
                threadTwitter.Start();

                // Start Story Thread
                Thread threadStory = new Thread(new ThreadStart(LoadStory));
                threadStory.Priority = ThreadPriority.BelowNormal;
                threadStory.Start();

                m_updated = ReloadScoreboard(null);
                if (m_mainChannel.ScoreBoard.GamesList.Games.Count > 0)
                {
                    // THERE ARE GAMES!
                    if (ToolBox.YesterdayScores())
                    {
                        m_currentView = VIEWS.MORNINGVIEW;
                    }
                    else
                    {
                        m_currentView = VIEWS.GAMEVIEW;
                    }
                    m_mainChannel.UpdateBoxscore(m_currentDate);
                    m_boxesManager.InitializeBoxedGames(m_mainChannel.ScoreBoard);
                    m_mainChannel.UpdateAllBoxscores(m_currentDate, m_mainChannel.ScoreBoard);
                }

                while (true)
                {
                    if (m_requireRefresh)
                    {
                        CreateDailyPaper(); 
                    }
                    Thread.Sleep(2000);
                }

            }
            catch (Exception ex)
            {
                Output.ERROR_MODE = true;
                Output.WriteLine("-- IGG ERROR --");
                Output.WriteLine(ex.Message);
                Output.WriteLine(ex.StackTrace);
                Output.WriteLine();
                Output.WaitForInput();
            }
        }

        /// <summary>
        /// Start threads to feed the news
        /// </summary>
        private void CreateDailyPaper()
        {
            int currentPage = 2;
            m_requireRefresh = false;
            Output.Clear();
            Output.WriteLine();
            Output.WriteLine(" =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Output.WriteLine(" THE DAILY FASTBALL - " + DateTime.Now.ToLongDateString());
            Output.WriteLine(" Last Updated on " + DateTime.Now.ToLongTimeString());
            Output.WriteLine(" =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            if (m_needBoxes && m_mainChannel.ScoreBoard.GamesList.Games.Count > 0)
            {
                m_boxesManager.BuildBoxes(m_mainChannel.ScoreBoard);
                Output.WriteLine();
                Player[] stars = ThreeStarsCalculator.GetThreeStarPlayers(m_mainChannel.ScoreBoard.GamesList.Games);
                if (stars[0] != null && stars[0].GameScore > 0)
                {
                    ModeOverviewFormatter.FormatStar(1, stars[0]);
                    ModeOverviewFormatter.FormatStar(2, stars[1]);
                    ModeOverviewFormatter.FormatStar(3, stars[2]);

                    for (int i = 0; i < 3; i++)
                    {
                        if (m_mainChannel.ScoreBoard.GamesList.SortedGames.Count > i)
                        {
                            if (ToolBox.YesterdayScores() == false && m_mainChannel.ScoreBoard.GamesList.SortedGames[i].Status.Indicator.IsInProgress)
                            {
                                ModeOverviewFormatter.FormatInProgressGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[i]);
                            }
                            else if (m_mainChannel.ScoreBoard.GamesList.SortedGames[0].Status.Indicator.IsTerminated)
                            {
                                ModeOverviewFormatter.FormatTerminatedGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[i], ToolBox.YesterdayScores());
                            }
                        }
                    }
                }
                else
                {
                    string start = "Games will start at " + m_mainChannel.ScoreBoard.GamesList.Games[0].StartTime
                        + " " + m_mainChannel.ScoreBoard.GamesList.Games[0].AmPm.ToLower() + ". "
                        + m_mainChannel.ScoreBoard.GamesList.Games.Count + " games today.";
                    Output.FormatLongText(start);
                    Output.WriteLine();
                    ModeOverviewFormatter.FormatNextGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[0]);
                }
                PrintFooter(currentPage++);
            }

            if (m_mainChannel.ScoreBoard.SelectedGame!=null)
            {
                ModeDetailedGameFormatter formatter = new ModeDetailedGameFormatter();
                formatter.FormatMode(m_mainChannel.ScoreBoard);
                PrintFooter(currentPage++);
            }


            // NEWS
            if (m_mainChannel.ScoreBoard.News != null && m_mainChannel.ScoreBoard.News.Count > 2)
            {
                for (int i = 0; i < 5; i++)
                {
                    Output.WriteLine();
                    Output.WriteLine(" " + m_mainChannel.ScoreBoard.News[i].Title.ToUpper());
                    Output.FormatLongText(m_mainChannel.ScoreBoard.News[i].Content);
                }
            }
            PrintFooter(currentPage++);

            //  TWITTER
            if (m_mainChannel.ScoreBoard.Tweets != null && m_mainChannel.ScoreBoard.Tweets.Length > 0)
            {
                Output.WriteLine();
                for (int i = 0; i < 7; i++)
                {
                    Output.WriteLine(" " + m_mainChannel.ScoreBoard.Tweets[i].Author.ToUpper());
                    Output.FormatLongText(m_mainChannel.ScoreBoard.Tweets[i].Text);
                    Output.WriteLine();
                }
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" FROM THE TWITTERVERSE  (Not Currently Available)");
            }
            PrintFooter(3);

            // TRANSACTIONS
            if (m_mainChannel.ScoreBoard.Transactions != null && m_mainChannel.ScoreBoard.Transactions.Count > 0)
            {
                new ModeTransactionsFormatter().FormatMode(m_mainChannel.ScoreBoard, 12);
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" TRANSACTIONS (Not Currently Available)");
            }
            PrintFooter(currentPage++);

            // HISTORY
            Output.WriteLine();
            Output.WriteLine(" DID YOU KNOW?");
            Output.FormatLongText(m_mainChannel.GetHistoryTidbit());

            FormatBillJames();

            // BASEBALL REFERENCE
            if (m_mainChannel.ScoreBoard.BaseballRefTidbit != null)
            {
                Output.WriteLine();
                Output.WriteLine(" FROM BASEBALL REFERENCE...");
                Output.WriteLine(m_mainChannel.ScoreBoard.BaseballRefTidbit);
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" FROM BASEBALL REFERENCE (Not Currently Available)");
            }
            PrintFooter(currentPage++);

            // STANDINGS
            if (m_mainChannel.ScoreBoard.StandingsNLC != null && m_mainChannel.ScoreBoard.StandingsNLC.Count > 0)
            {
                Output.WriteLine();
                if (m_mainChannel.ScoreBoard.StatsBatting != null && m_mainChannel.ScoreBoard.StatsBatting.Count > 0)
                {
                    standingsFormatter.FormatCombinedMode(m_mainChannel.ScoreBoard);
                }
                else
                {
                    standingsFormatter.FormatMode(m_mainChannel.ScoreBoard);
                }
            }
            else if (m_mainChannel.ScoreBoard.StandingsGrapefruit != null && m_mainChannel.ScoreBoard.StandingsGrapefruit.Count > 0)
            {
                standingsFormatter.FormatCombinedSpringTraining(m_mainChannel.ScoreBoard);
            }
            else
            {
                Output.WriteLine();
                Output.WriteLine(" STANDINGS (Not Currently Available)");
            }

            // STATS
            if (m_mainChannel.ScoreBoard.StatsBatting == null || m_mainChannel.ScoreBoard.StatsBatting.Count == 0)
            {
                Output.WriteLine();
                Output.WriteLine(" STATISTICS (Not Currently Available)");
            }
            PrintFooter(currentPage++);
            Output.WriteLine();
            if (teamSectionManager.Ready)
            {
                teamSectionManager.PublishTeamSection();
            }
            PrintFooter(currentPage++);

            if (m_story != null)
            {
                Output.WriteLine();
                Output.FormatLongText(m_story);
                PrintFooter(8);
            }

            storyManager.FormatStory();
            PrintFooter(currentPage++);
        }

        private void FormatBillJames()
        {
            Player player = m_billJamesParser.GetPlayerTidbit();
            Output.WriteLine();
            Output.WriteLine(" BILL JAMES HISTORICAL BASEBALL ABSTRACT");
            string pos = "Pitcher";
            if (player.Position == "C")
            {
                pos = "Catcher";
            }
            if (player.Position == "1B")
            {
                pos = "First Base";
            }
            if (player.Position == "2B")
            {
                pos = "Second Base";
            }
            if (player.Position == "3B")
            {
                pos = "Third Base";
            }
            if (player.Position == "SS")
            {
                pos = "Shortstop";
            }
            if (player.Position == "LF")
            {
                pos = "Leftfield";
            }
            if (player.Position == "CF")
            {
                pos = "Centerfield";
            }
            if (player.Position == "RF")
            {
                pos = "Rightfield";
            }
            if (player.Position == "SP")
            {
                pos = "Pitcher";
            }
            if (player.Position == "CL")
            {
                pos = "Closer";
            }

            string text = " " + "#" + player.Number + " " + pos + " - " +player.NameDisplay;
            Output.WriteLine(text);
            Output.FormatLongText(player.Report.Trim());
        }

        private void PrintFooter(int page)
        {
            Output.WriteLine("                                                                                                                                                                     p. " + page);
            Output.WriteLine(" =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

        }

        private void LoadStandings()
        {
            Thread.Sleep(3 * 1000);
            m_mainChannel.UpdateStandings();
            m_requireRefresh = true;
        }

        private void LoadStory()
        {
            Thread.Sleep(10 * 1000);
            //storyManager.FormatStory();
            m_requireRefresh = true;
        }

        private void LoadStats()
        {
            Thread.Sleep(10 * 1000);
            m_mainChannel.UpdateStatistics();
            m_requireRefresh = true;
        }

        private void LoadBaseballRefTidbit()
        {
            Thread.Sleep(5 * 1000);
            m_mainChannel.SetBaseballReferenceTidbit();
            m_requireRefresh = true;
        }

        private void LoadNews()
        {
            m_mainChannel.UpdateNews(false);
            m_requireRefresh = true;
        }

        private void LoadTeamSection()
        {
            while (true)
            {
                teamSectionManager.LoadTeamSection();
                m_requireRefresh = true;
                Thread.Sleep(15 * 60 * 1000);
            }
        }

        private void LoadTwitter()
        {
            while(true)
            {
                Thread.Sleep(5 * 60 * 1000);
                m_mainChannel.UpdateTweets();
                m_requireRefresh = true;
            }

        }

        private void LoadTransactions()
        {
            Thread.Sleep(2 * 1000);
            m_mainChannel.UpdateTransactions();
            m_requireRefresh = true;
        }






        /// <summary>
        /// Start threads to feed the news
        /// </summary>
        private void StartGamesThreads()
        {
            m_mainChannel.UpdateNews(false);
            m_mainChannel.UpdateTweets();
            m_mainChannel.UpdateTransactions();
            Output.Clear();

            m_mainChannel.UpdateBoxscore(m_currentDate);
            m_boxesManager.InitializeBoxedGames(m_mainChannel.ScoreBoard);
            m_mainChannel.UpdateAllBoxscores(m_currentDate, m_mainChannel.ScoreBoard);

            if (m_needBoxes && m_mainChannel.ScoreBoard.GamesList.Games.Count > 0)
            {
                m_boxesManager.BuildBoxes(m_mainChannel.ScoreBoard);
                Output.WriteLine();
            }

            Player[] stars = ThreeStarsCalculator.GetThreeStarPlayers(m_mainChannel.ScoreBoard.GamesList.Games);
            if (stars[0] != null && stars[0].GameScore > 0)
            {
                ModeOverviewFormatter.FormatStar(1, stars[0]);
                ModeOverviewFormatter.FormatStar(2, stars[1]);
                ModeOverviewFormatter.FormatStar(3, stars[2]);

                for (int i = 0; i < 3; i++)
                {
                    if (m_mainChannel.ScoreBoard.GamesList.SortedGames.Count > i)
                    {
                        if (ToolBox.YesterdayScores() == false && m_mainChannel.ScoreBoard.GamesList.SortedGames[i].Status.Indicator.IsInProgress)
                        {
                            ModeOverviewFormatter.FormatInProgressGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[i]);
                        }
                        else if (m_mainChannel.ScoreBoard.GamesList.SortedGames[0].Status.Indicator.IsTerminated)
                        {
                            ModeOverviewFormatter.FormatTerminatedGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[i], true);
                        }
                    }
                }
            }
            else
            {
                string start = "Games will start at " + m_mainChannel.ScoreBoard.GamesList.Games[0].StartTime
                    + " " + m_mainChannel.ScoreBoard.GamesList.Games[0].AmPm.ToLower() + ". "
                    + m_mainChannel.ScoreBoard.GamesList.Games.Count + " games today.";
                Output.FormatLongText(start);
                Output.WriteLine();
                ModeOverviewFormatter.FormatNextGame(m_mainChannel.ScoreBoard.GamesList.SortedGames[0]);
            }
            if (m_mainChannel.ScoreBoard.Tweets != null && m_mainChannel.ScoreBoard.Tweets.Length > 0)
            {
                for (int i = 0; i < 5; i++)
                {
                    Output.FormatLongText(m_mainChannel.ScoreBoard.Tweets[i].Author.ToUpper().PadRight(20) + ": " + m_mainChannel.ScoreBoard.Tweets[i].Text);
                }
            }
            if (m_mainChannel.ScoreBoard.News != null && m_mainChannel.ScoreBoard.News.Count > 2)
            {
                for (int i = 0; i < 3; i++)
                {
                    Output.WriteLine();
                    Output.WriteLine(" " + m_mainChannel.ScoreBoard.News[i].Title.ToUpper());
                    Output.FormatLongText(m_mainChannel.ScoreBoard.News[i].Content);
                }
            }

            new ModeTransactionsFormatter().FormatMode(m_mainChannel.ScoreBoard, 6);
            m_mainChannel.LoadHistory();
            Output.FormatLongText(m_mainChannel.ScoreBoard.History[0]);
            //Output.WriteLine(m_mainChannel.SetBaseballReferenceTidbit());
        }


        /// <summary>
        /// Reload the scoreboard as many times as necessary
        /// </summary>
        public bool ReloadScoreboard(string selectedId)
        {
            int maxTries = 8;
            int currentTry = 1;
            int currentDelay = 1000;
            bool success = false;
            while (success == false && currentTry <= maxTries)
            {
                try
                {
                    m_mainChannel.RefreshScoreboard(m_currentDate, selectedId);
                    success = true;
                }
                catch
                {
                    Thread.Sleep(currentDelay);
                    currentDelay = currentDelay * 2;
                }
                finally
                {
                    currentTry++;
                }
            }
            return success;
        }

        /// <summary>
        /// Triggers a data update
        /// </summary>
        /// <param name="key"></param>
        private void UpdateModeData(ConsoleKey key)
        {
            m_needBoxes = true;
            if (key == ConsoleKey.D1 || key == ConsoleKey.D2 || key == ConsoleKey.D3 ||
                key == ConsoleKey.D4 || key == ConsoleKey.D5 || key == ConsoleKey.D6 ||
                key == ConsoleKey.D7 || key == ConsoleKey.D8 || key == ConsoleKey.D9 || key == ConsoleKey.D0)
            {
                if (m_statsLoaded == false)
                {
                    m_mainChannel.UpdateStatistics();
                    m_statsLoaded = true;
                }
            }
            else if (key == ConsoleKey.S || key == ConsoleKey.A)
            {
                m_mainChannel.UpdateStandings();
            }
            else if (key == ConsoleKey.H)
            {
                m_mainChannel.LoadHistory();
            }
            else if (key == ConsoleKey.L || key == ConsoleKey.D)
            {
                m_mainChannel.UpdateTeamAlignment(m_currentDate);
            }
            else if (key == ConsoleKey.B)
            {
                m_mainChannel.UpdateBoxscore(m_currentDate);
            }
            else if (key == ConsoleKey.N)
            {
                m_mainChannel.UpdateNews(false);
            }
            else if (key == ConsoleKey.M)
            {
                m_mainChannel.UpdateTeam();
            }
            else if (key == ConsoleKey.J)
            {
                m_mainChannel.UpdateInjuries();
            }
            else if (key == ConsoleKey.F)
            {
                m_mainChannel.UpdateBaseballReference();
            }
            else if (key == ConsoleKey.R)
            {
                m_mainChannel.UpdateTransactions();
            }
            else if (key == ConsoleKey.Z)
            {
                CreateDailyPaper();
            }
            else if (key == ConsoleKey.W)
            {
                m_twitterThreadActive = true;
                m_twitterThread = new Thread(new ThreadStart(RunTwitterThread));
                m_twitterThread.Start();
            }
            else if (key == ConsoleKey.O)
            {
                //m_needBoxes = false;
                m_mainChannel.UpdateTweets();
                m_mainChannel.UpdateAllBoxscores(m_currentDate, m_mainChannel.ScoreBoard);
                m_mainChannel.UpdateNews(false);
            }
        }

        private void RunTwitterThread()
        {
            while (m_twitterThreadActive)
            {
                Output.Clear();
                Output.WriteLine("");
                Output.WriteLine(" Loading Tweets...");
                Output.WriteLine("");
                Output.WriteLine(" Please wait.");
                Output.Clear();
                m_mainChannel.UpdateTweets();
                for (int i = 0; i < 12; i++)
                {
                    Output.WriteLine();
                    Output.WriteLine(" " + m_mainChannel.ScoreBoard.Tweets[i].Author.ToUpper());
                    Output.FormatLongText(m_mainChannel.ScoreBoard.Tweets[i].Text);
                }
                Thread.Sleep(120000);
            }
        }



        /// <summary>
        /// Manage the refreshed event from the main channel
        /// </summary>
        private void m_mainChannel_ScoreboardRefreshed(object sender, EventArgs e)
        {
            m_updated = true;
        }


        /// <summary>
        /// Show the command line game view
        /// </summary>
        /// <param name="scoreboard"></param>
        private void ShowGameView()
        {
            if (Modes.CurrentMode.AssociatedKey != ConsoleKey.W)
            {
                Output.Clear();
                string title = "MLB Scoreboard for " + ToolBox.GetFormattedDate(m_mainChannel.ScoreBoard.Date)
                    + " (updt @ " + m_mainChannel.ScoreBoard.LastUpdate.ToString("h:mm:ss") + ")";
                Output.SetTitle(title);
                if (m_needBoxes && m_mainChannel.ScoreBoard.GamesList.Games.Count > 0)
                {
                    m_boxesManager.BuildBoxes(m_mainChannel.ScoreBoard);
                    Output.WriteLine();
                }
                Modes.CurrentMode.ModeFormatter.FormatMode(m_mainChannel.ScoreBoard);
            }
        }

    }
}
